import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);

/**
 * 将秒数格式化为 mm:ss 或 hh:mm:ss 的字符串
 * @param totalSeconds 总秒数
 * @returns 格式化后的时间字符串
 */

export function formatTime(seconds: number, format?: string) {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;

  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;

  // 格式化输出为 mm:ss
  const formattedTime = dayjs()
    .hour(hours)
    .minute(remainingMinutes)
    .second(remainingSeconds)
    .format(format ?? 'mm:ss');

  return formattedTime;
}

/**
 * @deprecated
 * app时间戳，根据规则转换为对应的本文字符串
 * 支持：number | string
 */
export const generateTimeText = (timestamp?: number | string): string => {
  if (!timestamp) {
    return '';
  }
  const originalTime = new Date(timestamp);
  // 获取当前时区的偏移量（单位为分钟）
  const offset = originalTime.getTimezoneOffset();
  // 将时间对象的时区偏移量调整为当前时区的偏移量
  const convertedTime = new Date(originalTime.getTime() - offset * 60000);
  const time = dayjs(convertedTime);
  const now = dayjs();

  const nowYear = now.year();
  const timeYear = time.year();
  const nowMonth = now.month() + 1;
  const timeMonth = time.month() + 1;
  const nowDate = now.date();
  const timeDate = time.date();

  // 同一天 (年月日相同)
  if (nowDate === timeDate && nowMonth === timeMonth && nowYear === timeYear) {
    // 时间
    return time.format('HH:mm');
  }
  // 昨天
  if (nowDate - timeDate === 1 && nowMonth === timeMonth && nowYear === timeYear) {
    // 昨天+时间
    return 'yesterday ' + time.format('HH:mm');
  }

  if (nowDate - timeDate < 7 && nowMonth === timeMonth && nowYear === timeYear) {
    // 星期几+时间
    return time.format('dddd HH:mm');
  }

  if (nowDate - timeDate > 7 && now.year === time.year) {
    // 月日
    return time.format('MM-DD');
  }

  if (nowDate - timeDate > 7 && now.year !== time.year) {
    // 年月日
    return time.format('YYYY-MM-DD');
  }

  return time.format('YYYY-MM-DD');
};
